<?php namespace App\Repositories\Eloquent\User;

use App\Models\SocialiteUser;
use App\Models\SocialiteUserParam;
use App\Repositories\User\SocialiteUserRepositoryInterface;

class SocialiteUserRepository implements SocialiteUserRepositoryInterface
{
    /**
     * @param $id
     *
     * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Model[]|null
     */
    public function show($id)
    {
        return SocialiteUser::find($id);
    }

    /**
     * 查找第三方用户,不过不能存在,则创建
     *
     * @param Entity\SocialiteUser $socialite_user
     *
     * @return \Illuminate\Database\Eloquent\Model
     */
    public function createOrFind(Entity\SocialiteUser $socialite_user)
    {
        $user = SocialiteUser::query()->where([
            'uid' => $socialite_user->uid,
        ])->first();

        if (!$user) {
            $user = new SocialiteUser();
            $user->fill(array_filter($socialite_user->toArray()));

            $user->save();
        }

        $socialite_user->user_id = $user->user_id;
        (new SocialiteUserParam())->fill([
            'socialite_id' => $user->id,
            'params'       => $socialite_user->toArray(),
        ])->save();

        return $user;
    }

    /**
     * @param int|SocialiteUser $model
     * @param                   $user_id
     *
     * @return bool
     */
    public function bindUser($model, $user_id)
    {
        if (!($model instanceof SocialiteUser)) {
            $model = $this->show((int)$model);
        }

        $model->user_id = $user_id;

        return $model->save();
    }

    /**
     * 获取用户在微信公众平台的open id
     *
     * @param $user_id
     *
     * @return string|null
     */
    public function getWechatMpOpenId($user_id)
    {
        $user = $this->getUserByUserId($user_id);
        if ($user) {
            return $user->open_id;
        }
    }

    /**
     * 通过user_id获取第三方用户信息
     *
     * @param $user_id
     *
     * @return mixed
     */
    public function getUserByUserId($user_id)
    {
        return SocialiteUser::query()
            ->where('user_id', $user_id)
            ->first();
    }

}
